package com.cskaoyan.service;

import com.cskaoyan.bean.Brand;
import com.cskaoyan.bean.BrandData;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.bean.params.BaseParam;
import com.cskaoyan.mapper.BrandMapper;
import com.cskaoyan.mapper.StorageMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Tangyin
 * @description品牌制造商
 * @since 2022/05/06 14:29
 */
@Service
public class AdminBrandServiceImpl implements AdminBrandService {
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    StorageMapper storageMapper;

    @Override
    public BrandData query(BaseParam param, Integer id, String name) {
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        String sort = param.getSort();
        String order = param.getOrder();
        PageHelper.startPage(page, limit);
        List<Brand> list = brandMapper.select(sort, order, id, name);

        PageInfo<Brand> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return BrandData.data(total, pages, limit, page, list);
    }

    @Override
    public Brand update(Brand brand) {
        brand.setUpdateTime(new Date(System.currentTimeMillis()));
        int affectedRows = brandMapper.updateByPrimaryKeySelective(brand);
        if (affectedRows == 1) {
            return brand;
        }
        return null;
    }

    @Override
    public int createBrand(Brand brand) {
        int i = brandMapper.insertSelective(brand);
        return i;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Integer insertStorage(Storage storage) {
        storageMapper.insertSelective(storage);
        Integer id = storage.getId();
        return id;
    }

    @Override
    public Integer deleteBrandById(Integer id) {
        int i = brandMapper.deleteByPrimaryKey(id);
        return i;
    }
}
